package com.quectel.grid.controller.grid;

import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.business.common.grid.GridBusiness;
import com.quectel.constant.core.grid.GridConstant;
import com.quectel.constant.global.SystemConstants;
import com.quectel.core.module.grid.dto.*;
import com.quectel.core.module.grid.service.GridNoticeRelationService;
import com.quectel.core.module.grid.service.GridNoticeService;
import com.quectel.core.module.grid.service.GridService;
import com.quectel.grid.controller.BaseController;
import com.quectel.grid.util.SessionHolder;
import com.quectel.util.common.Page;
import com.quectel.util.common.Request;
import com.quectel.util.common.Response;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author caolu
 * @email louis.cao@quectel.com
 */
@RestController
@RequestMapping("gridNotice")
@Tag(name = "GridNoticeController", description = "网格公告相关API")
public class GridNoticeController extends BaseController {

    @DubboReference
    private GridNoticeService gridNoticeService;
    @DubboReference
    private GridNoticeRelationService gridNoticeRelationService;
    @DubboReference
    private GridService gridService;
    @Autowired
    private GridBusiness gridBusiness;


    /**
     * 详情
     *
     * @param id
     * @return
     */
    @GetMapping("info/{id}")
    @Operation(summary = "查询单条记录,gridNoticeRelation的Id")
    public Response<GridNoticeRelationDto> info(@PathVariable("id") Long id) {
        GridMemberDto gridMember = SessionHolder.getGridMember();

        Map<String, Object> params = new HashMap<>();
        params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));
        params.put(LambdaUtil.getFieldName(GridNoticeRelationDto::getTenantId), gridMember.getTenantId());
        //筛选启用状态
        params.put(LambdaUtil.getFieldName(GridNoticeDto::getStatus), SystemConstants.COMMON);
        if (gridNoticeRelationService.queryTotal(params) <= 0) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }

        GridNoticeRelationDto gridNoticeRelationDto = gridNoticeRelationService.selectById(id);
        if (gridNoticeRelationDto == null) {
            return Response.error("未查询到公告详情");
        }

        List<GridDto> myGrids = gridBusiness.getMyGrids(gridMember.getId());
        List<String> collect = myGrids.stream().map(dto -> String.valueOf(dto.getId())).collect(Collectors.toList());
        if (!collect.contains(gridNoticeRelationDto.getSourceId())) {
            return Response.error(SystemConstants.ILLEGAL_MSG);
        }
        GridNoticeDto noticeDto = gridNoticeService.selectCacheById(gridNoticeRelationDto.getGridNoticeId());
        gridNoticeRelationDto.setGridNotice(noticeDto);
        gridNoticeRelationDto.setGridRegionInfo(packRegionInfo(gridNoticeRelationDto.getSourceType(), gridNoticeRelationDto.getSourceId()));

        //更新已读状态
        if (SystemConstants.NO.equals(gridNoticeRelationDto.getReadStatus())) {
            gridNoticeRelationDto.setReadStatus(SystemConstants.YES);
            gridNoticeRelationService.updateById(gridNoticeRelationDto);
        }

        return Response.<GridNoticeRelationDto>ok().wrap(gridNoticeRelationDto);
    }

    /**
     * 网格通知列表
     *
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("parentList")
    @Operation(summary = "上级通知列表")
    public Response<Page<GridNoticeRelationDto>> parentList(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "网格ID") @RequestParam(required = false) Long gridId
    ) {
        GridMemberDto gridMember = SessionHolder.getGridMember();

        //查询列表数据
        Request request = Request.configParams(Request.parseParams(httpServletRequest));
        List<GridDto> myGrids = gridBusiness.getMyGrids(gridMember.getId());
        if (CollectionUtils.isEmpty(myGrids)) {
            Page<GridNoticeRelationDto> page = new Page<>(request.getPageNo(), request.getPageSize(), 0, Collections.emptyList());
            return Response.<Page<GridNoticeRelationDto>>ok().wrap(page);
        }

        request.put(LambdaUtil.getFieldName(GridNoticeRelationDto::getSourceType), GridConstant.RegionLevel.GRID_LEVEL.getLevel());
        if (gridId != null) {
            request.put(LambdaUtil.getFieldName(GridNoticeRelationDto::getSourceId), String.valueOf(gridId));
        } else {
            List<String> collect = myGrids.stream().map(dto -> String.valueOf(dto.getId())).collect(Collectors.toList());
            request.put(GridConstant.SOURCE_IDS, collect);
        }

        //筛选启用状态
        request.put(LambdaUtil.getFieldName(GridNoticeDto::getStatus), SystemConstants.COMMON);

        int total = gridNoticeRelationService.queryTotal(request.getParams());

        List<GridNoticeRelationDto> list = null;
        if (total > 0) {
            list = gridNoticeRelationService.queryList(request.getParams());
            list.forEach(gridNoticeRelationDto -> {
                gridNoticeRelationDto.setGridRegionInfo(packRegionInfo(gridNoticeRelationDto.getSourceType(), gridNoticeRelationDto.getSourceId()));
                gridNoticeRelationDto.setGridNotice(gridNoticeService.selectCacheById(gridNoticeRelationDto.getGridNoticeId()));
            });
        } else {
            list = new ArrayList<>();
        }

        Page<GridNoticeRelationDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, list);
        return Response.<Page<GridNoticeRelationDto>>ok().wrap(page);
    }

    private GridRegionInfoDto packRegionInfo(Byte regionLevel, String regionCode) {
        if (GridConstant.RegionLevel.GRID_LEVEL.getLevel().equals(regionLevel)) {
            GridDto gridDto = gridService.selectCacheById(Long.valueOf(regionCode));
            if (gridDto != null) {
                return GridRegionInfoDto.builder()
                        .level(GridConstant.RegionLevel.GRID_LEVEL.getLevel())
                        .name(gridDto.getVillage() != null ? gridDto.getVillage().getName() + gridDto.getName() : gridDto.getName())
                        .code(String.valueOf(gridDto.getId()))
                        .build();
            }

        }
        return null;
    }
}
